<template>
    <div ref="watermarkContainer" class="watermark-container">
        <!-- 插槽内容，可以放置需要水印的内容 -->
        <slot></slot>
    </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref, Ref, watch } from "vue";
// 定义Props
// defineProps<{ watermarkText: string }>();
const props = defineProps({
    watermarkText: {
        type: String,
        required: true,
        default: "默认水印",
    },
});
// const watermarkUrl: Ref<string> = ref("");
const watermarkContainer = ref<HTMLElement | null>(null);
const watermark = ref<HTMLDivElement | null>(null);
const drawWatermark = () => {
    console.log("drawWatermark----");
    const watermarkImage = getWatermarkImage();
    if (watermark.value) {
        watermark.value.remove();
    }
    watermark.value = document.createElement("div");
    watermark.value.style.position = "absolute";
    watermark.value.style.backgroundImage = `url(${watermarkImage})`;
    watermark.value.style.backgroundSize = "200px 200px";
    watermark.value.style.backgroundRepeat = "repeat";
    // watermark.value.style.opacity = "0.5";
    watermark.value.style.zIndex = "99";
    watermark.value.style.pointerEvents = "none";
    watermark.value.style.transform = "rotate(-45deg)";
    watermark.value.style.inset = "0";
    watermarkContainer.value?.appendChild(watermark.value);
};
const getWatermarkImage = () => {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    if (!ctx) return;
    canvas.width = 200;
    canvas.height = 150;
    ctx.font = "16px Arial";
    ctx.fillStyle = "rgba(184, 184, 184, 0.5)";
    // ctx.textAlign = "center";
    ctx.fillText(props.watermarkText, 20, 100);
    return canvas.toDataURL("image/png");
};

const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
        console.log(mutation);
        if (
            mutation.type === "attributes" ||
            mutation.attributeName === "style"
        ) {
            drawWatermark();
        }
    });
});

onMounted(() => {
    drawWatermark();
    if (watermarkContainer.value) {
        observer.observe(watermarkContainer.value, {
            childList: true,
            subtree: true,
            attributes: true,
            // attributeFilter: ["style"],
        });
    }

    watch(
        () => props.watermarkText,
        () => {
            drawWatermark();
        },
    );
});
onUnmounted(() => {
    observer.disconnect();
});
</script>

<style>
.watermark-container {
    position: relative;
    width: 100%;
    height: 100%;
}
</style>
